package com.jse.mvc;

import java.util.Arrays;
import java.util.LinkedHashMap;

import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;

import com.jse.plug.JseSession;
import com.jse.service.NashornService;
import com.jse.view.captcha.CaptchaView;

@IocBean
public class ToolsAction {

	Log log = Logs.get();
	@Inject
	NashornService nashornService;

	@At("/captcha/*")
	public View captcha(int length) {
		// CaptchaView.CAPTCHA KERBORES_NUTZ_CAPTCHA 在session中的key
		return new CaptchaView(null, length);
	}

	/**
	 * 服务端json
	 * 
	 * @param actionName
	 * @param methodName
	 * @param page
	 * @param req
	 * @param resp
	 * @param session
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@At({ "/raw/?/?", "/json/?/?" })
	@Ok("json")
	public Object raw(String actionName, String methodName, String raw, HttpServletRequest req,
			HttpServletResponse resp,JseSession session) {
		Object rtv = null;
		try {
			NutMap param = new NutMap();
			req.getParameterMap().forEach((k, v) -> {
				if(k.startsWith("{")&&k.endsWith("}")) {
					param.putAll(Json.fromJson(LinkedHashMap.class,k));
				}else {
					param.put(k, v.length > 1 ? Arrays.asList(v) : v[0]);
				}
			});
			rtv = nashornService.run(actionName, methodName, param,session);
			resp.setHeader("Access-Control-Allow-Origin", "*");
			resp.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
			resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
			return rtv;
		} catch (NoSuchMethodException | ScriptException e) {
			// TODO 执行脚本的错误待处理
			log.error(e);
			return null;
		} finally {

		}
	}
}
